package com.future;

/**
 * Description: 443. 压缩字符串
 * 做法跟 《面试题 01.06. 字符串压缩》 类似
 *
 * @author weiruibai.vendor
 * Date: 2022/11/10 14:14
 */
public class Solution_443 {

    static Solution_443 instance = new Solution_443();

    public static void main(String[] args) {
        //System.out.println("adf434".length());
        char[] chars = new char[]{'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'};

        chars = new char[]{'a', 'a', 'b', 'b', 'c', 'c', 'c'};
        //System.out.println(instance.compress(chars));
        System.out.println(instance.compress_v2(chars));
    }

    /**
     * 直接在原来数组改
     *
     * @param chars
     * @return
     */
    public int compress_v2(char[] chars) {
        if (chars.length < 2) {
            return chars.length;
        }
        int N = chars.length;
        int validIndex = 0;
        for (int i = 0; i < N; ) {
            chars[validIndex++] = chars[i];
            int count = 1;
            int j = i + 1;
            while (j < N && chars[i] == chars[j]) {
                count++;
                j++;
            }
            if (count != 1) {
                char[] countStr = String.valueOf(count).toCharArray();
                if (countStr.length > 1) {
                    for (int k = 0; k < countStr.length; k++) {
                        chars[validIndex++] = countStr[k];
                    }
                } else {
                    chars[validIndex++] = countStr[0];
                }
            }
            i = j;
        }
        return validIndex;
    }

    public int compress(char[] chars) {
        if (chars.length < 2) {
            return chars.length;
        }
        int N = chars.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < N; ) {
            sb.append(chars[i]);
            int count = 1;
            int j = i + 1;
            while (j < N && chars[i] == chars[j]) {
                count++;
                j++;
            }
            if (count != 1) {
                sb.append(count);
            }
            i = j;
        }
        char[] chars1 = sb.toString().toCharArray();
        for (int i = 0; i < chars1.length; i++) {
            chars[i] = chars1[i];
        }
        return sb.toString().length();
    }
}
